package cn.boodqian.airdata;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.logging.Logger;

import javax.servlet.http.*;

import com.google.gson.Gson;

public class LocationServlet extends HttpServlet {
	private final static Logger Log = Logger.getLogger(LocationServlet.class.getName());
	private final static int code = 3;
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		resp.setContentType("text/plain");
		resp.setCharacterEncoding("UTF-8");
		
		String path = req.getPathInfo();
		Log.info(path);
		
		if( path == null ) {
			resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
			return;
		}
		
		if( path.compareTo("/list")==0 ) {
			String locations = null;

			String lang = req.getParameter("lang");
			ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
			if(lang!=null && lang.compareTo("en")==0) {
			    list.addAll(BeijingAirDataProvider.locationList_en);
				list.addAll(ShanghaiAirDataProvider.locationList_en);
				list.addAll(ShanghaiUSAirDataProvider.locationList_en);
			} else {
			    list.addAll(BeijingAirDataProvider.locationList);
				list.addAll(ShanghaiAirDataProvider.locationList);
				list.addAll(ShanghaiUSAirDataProvider.locationList);
			}
			ArrayList<HashMap<String, String>> cnemc_list = CNEMCAirDataProvider.getLocationList(lang);
			if( cnemc_list != null ) list.addAll(cnemc_list);

			if(list.size()>0)
				locations = new Gson().toJson(list);

			if(locations == null)
				resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
			else
				resp.getWriter().println(locations);
		} else if( path.compareTo("/code")==0 ) {
			String ret = new Gson().toJson(code);
			resp.getWriter().print(ret);
		}
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws IOException
	{
		doGet(req, resp);
	}
}
